package cn.wolfcode.trip.app.controller;

import cn.wolfcode.trip.base.domain.Region;
import cn.wolfcode.trip.base.domain.Strategy;
import cn.wolfcode.trip.base.query.StrategyQuery;
import cn.wolfcode.trip.base.service.IRegionService;
import cn.wolfcode.trip.base.service.IStrategyService;
import com.github.pagehelper.PageInfo;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("regions")
public class RegionController {

    @Autowired
    private ServletContext ctx;

    @Autowired
    private IRegionService regionService;
    @Autowired
    private IStrategyService strategyService;

    @GetMapping
    public List<Region> list(){
        return regionService.selectAll();
    }

    @GetMapping("/{state}")
    public Object list(@PathVariable int state){
        return regionService.list(state);
    }

    @GetMapping(value = "/{regionId}/strategies", produces = "text/html;charset=utf-8")
    public void strategyList(@PathVariable Long regionId, HttpServletResponse rep) throws Exception {
        //当季的推荐攻略,攻略中状态为推荐的攻略
        StrategyQuery query = new StrategyQuery();
         query.setState(Strategy.STATE_HOT);    //推荐状态
         query.setRegionId(regionId);
         query.setPageSize(0);  //不分页
        PageInfo commends = strategyService.selectForList(query);

        //查询所有游记,并且分页
        query.setRegionId(regionId);
        query.setState(-1);
        query.setPageSize(6);   //分页
        PageInfo all = strategyService.selectForList(query);



        //模板 + 数据 = 输出
        Configuration cfg = new Configuration(Configuration.VERSION_2_3_28);
        cfg.setDirectoryForTemplateLoading(new File(ctx.getRealPath("/template")));
        Template template = cfg.getTemplate("strategyPage.ftl");


        Map<String, Object> data = new HashMap<String, Object>();
        data.put("commends", commends);
        data.put("all", all);

        //输出到浏览器
        template.process(data, rep.getWriter());
    }

    //地区下攻略分页
    @GetMapping(value = "/{regionId}/strategies", produces = "application/json;charset=utf-8")
    public Object listStrategysJSON(StrategyQuery qo)throws Exception{

        return strategyService.selectForList(qo);

    }


    //一级联动
    @GetMapping("/app/{parentId}")
    public Object listRegionsByParentId(@PathVariable Long parentId){

        return  regionService.getRegionByParentId(parentId);
    }

}
